package com.sjh;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author jack
 */
public class ExchangerTest {
 
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final Exchanger exchanger = new Exchanger();
		service.execute(new Runnable() {
			@Override
			public void run() {
				try {
 
					String data1 = "zxx";
					System.out.println("线程" + Thread.currentThread().getName()
							+ "正在把数据" + data1 + "换出去");
					Thread.sleep((long) (Math.random() * 10000));
					/*
					 * 等待另一个线程到达此交换点（除非当前线程被中断），
					 * 然后将给定的对象传送给该线程，并接收该线程的对象。
					 */
					String data2 = (String) exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName()
							+ "换回的数据为" + data2);
				} catch (Exception e) {
 
				}
			}
		});
		service.execute(new Runnable() {
			@Override
			public void run() {
				try {
 
					String data1 = "lhm";
					System.out.println("线程" + Thread.currentThread().getName()
							+ "正在把数据" + data1 + "换出去");
					Thread.sleep((long) (Math.random() * 10000));
					String data2 = (String) exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName()
							+ "换回的数据为" + data2);
				} catch (Exception e) {
 
				}
			}
		});
	}
}
